package com.gjy.dubbo.service.util;

import okhttp3.*;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-06-12 13:43:40
 */
public class OkhttpUtil {

    static public OkHttpClient client;

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");


    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(60000L, TimeUnit.MILLISECONDS)
                .readTimeout(60000L, TimeUnit.MILLISECONDS)
                .build();
    }

    public static String get(String url) throws Exception {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        }
    }

    public static String get(String url, Map<String, String> params) throws Exception {
        HttpUrl.Builder queryUrlBuilder = HttpUrl.get(url).newBuilder();
        params.forEach(queryUrlBuilder::addQueryParameter);

        Request request = new Request.Builder()
                .url(queryUrlBuilder.build())
                .build();

        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        }

    }

    public static String post(String url, String json) throws Exception {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        }
    }

}
